package com.qf.zhijia.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.zhijia.mapper.FunSeacherMapper;
import com.qf.zhijia.pojo.Product;
import com.qf.zhijia.service.FunSeacherService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author 岳鹏
 * @Date 2020/9/8
 */
@Service
public class FunSeacherServiceImpl implements FunSeacherService {


    @Autowired
    RestTemplate restTemplate;

    @Autowired
    FunSeacherMapper funSeacherMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

    ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 全文检索
     * @param pName
     * @return
     */
    @Override
    public String searchAll(String pName) throws JsonProcessingException {
        System.out.println("开始访问ES："+pName);
        //访问的searchURL
        String url = "http://localhost:8081/zhijiaSearch/SerchPro";
        //设置头信息；告诉浏览器我这个请求时json格式
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        String json = objectMapper.writeValueAsString(pName);
        //将请求参数和请求头设置放入到HttpEntity中
        HttpEntity httpEntity = new HttpEntity(json,httpHeaders);
        //返回TempLate累心shuju
        return restTemplate.postForObject(url,httpEntity,String.class);
    }

    /**
     * 查询数据库数据，同步到ES中
     * @return
     */
    @Override
    public List<Product> synchronization() throws JsonProcessingException {
        List<Product> productList = funSeacherMapper.selectAll();
        System.out.println("查询到了数据库所有的商品数据如下："+productList);

//        String url = "http://localhost:8081/zhijiaSearch/add";
//        HttpHeaders httpHeaders = new HttpHeaders();
//        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
//        for (Product product : productList){
//            String json = objectMapper.writeValueAsString(product);
//            HttpEntity httpEntity = new HttpEntity(json,httpHeaders);
//            restTemplate.postForObject(url,httpEntity,String.class);
//        }

        //=============================
        System.out.println("开始同步到ES");
        //给ES发消息
        String json = objectMapper.writeValueAsString(productList);
        rabbitTemplate.convertAndSend("product-es-exchange","api.product.add",json);

        return productList;
    }
}
